package com.bjwl.web.contrlller.branchstore;

import com.alibaba.fastjson.JSONObject;
import com.bjwl.pojo.BranchStore;
import com.bjwl.pojo.Bsadmin;
import com.bjwl.pojo.Business;
import com.bjwl.pojo.IpRights;
import com.bjwl.pojo.dto.BsadminPowerDto;
import com.bjwl.pojo.vo.BsadminPowerVos;
import com.bjwl.service.*;
import com.bjwl.utils.HttpIpUtils;
import com.bjwl.utils.PageBean;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: czc
 * @Date:Create：in 2020/4/13 11:34
 * @Description:分店管理员web层
 * @Modified By：
 * @Version: 1.0
 */
@Controller
@RequestMapping("/bStoreMin")
public class BranchStoreMinControllerr {

    @Autowired
    private StaffController staffController;
    @Autowired
    private OrdersController ordersController;
    @Autowired
    private BusinessController businessController;
    @Autowired
    private BsadminService bsadminService;
    @Autowired
    private BranchStoreService branchStoreService;
    @Autowired
    private BsadminPowerService bsadminPowerService;
    @Autowired
    private IpRightsService ipRightsService;
    @Autowired
    private HttpIpUtils httpIpUtils;

    //登陆功能（根据用户名密码查找分店管理员）
    @RequestMapping("bStoreLogin")
    public @ResponseBody Integer byUsernameAndPasswordFindBsadmin(Bsadmin bsadmin, HttpSession httpSession, HttpServletRequest request) throws IOException {
        //管理员启用、禁用权限判断
        Bsadmin bsadmin1=bsadminService.findBsadminByUserNameAndPassWord(bsadmin);
        String ip = httpIpUtils.getIp(request);
        if(bsadmin1==null){
            return 0;
        }
        if(bsadmin1.getState() == null){
            return 0;
        }
        if(bsadmin1.getState() == 0){
            return 0;
        }
        if(ipRightsService.findIpRightByIpAndBsadmin(ip,bsadmin1.getId())){
            CloseableHttpClient aDefault = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true");
            CloseableHttpResponse response = aDefault.execute(httpGet);
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                //使用工具类EntityUtils，从响应中取出实体表示的内容并转换成字符串
                String string = EntityUtils.toString(entity, "utf-8");
                JSONObject jsonObject = JSONObject.parseObject(string);
                ipRightsService.addIpRight(httpIpUtils.getIp(request),bsadmin1.getId(),jsonObject.getString("addr"));
            }
            //5.关闭资源
            response.close();
            aDefault.close();

            return 2;
        }

        if(bsadmin1!=null){
            httpSession.setAttribute("bsadmin1",bsadmin1);

            Integer businessConunt = businessController.finBusinessCount(bsadmin1.getBsid());
            httpSession.setAttribute("businessConunt",businessConunt);

            Integer ordersCount = ordersController.finOrdersCount(bsadmin1.getBsid());
            httpSession.setAttribute("ordersCount",ordersCount);

            Integer staffCount = staffController.staffCount(bsadmin1.getBsid());
            httpSession.setAttribute("staffCount",staffCount);

            Integer bsadminCound = bsadminService.bsadminCound(bsadmin1.getBsid());
            httpSession.setAttribute("bsadminCound",bsadminCound);
            return 1;
        }
        return 0;

    };



    //查询当前登录管理员id
    @RequestMapping("bSByid")
     public  String byUsernameUpdate(Bsadmin bsadmin ,HttpSession httpSession) {
        Bsadmin bsadminUP = bsadminService.findBsadminById(bsadmin);
        httpSession.setAttribute("bsadminUP",bsadminUP);
        return "branch_oa/user-edit";
    }

    //修改当前管理员信息
    @RequestMapping("updateBsadminById")
    public @ResponseBody Boolean updateBsadminById(Bsadmin bsadmin){
        bsadminService.updateBsadminById(bsadmin);
        return true;
    }

    //切换账号(退出)
    @RequestMapping("bSJumpPage")
    public String bSJumpPage(){
        return "redirect:/br/login";
    }


    /**
     * 退出登录
     */
    @RequestMapping("/bSCancellation")
    public String bSCancellation(HttpSession session){
        session.removeAttribute("bsadmin");
        session.removeAttribute("bsadminUP");
        return "branch_oa/login";
    }

    /**
     * 根据当前登陆管理员id查询所有管理
     */
    @RequestMapping("findBsMinByBsid")
    public String findBsMinByBsid(HttpSession httpSession,Integer bsid){
        List<Bsadmin> bsadminsList = bsadminService.findBsMinByBsid(bsid);
        httpSession.setAttribute("bsadminsList",bsadminsList);
        return "branch_oa/admin-list";
    }

    //修改管理员信息(展示要修改的数据)
    @RequestMapping("updateShowBsadmin")
    public String updateShowBsadmin(HttpSession httpsession,Integer id){
        Bsadmin bsadmin = bsadminService.updateShowBsadmin(id);
        httpsession.setAttribute("bsadmin",bsadmin);
        return "branch_oa/admin-edit";
    }

    //添加管理员
    @RequestMapping("addBsadmin")
    public @ResponseBody Boolean addBsadmin(@RequestBody Bsadmin bsadmin){
        List<Bsadmin> bsadmins = bsadminService.findBsadminByName(bsadmin.getUsername());
        if(bsadmins.size()!=0 ){
            return false;
        }

        // new Date()为获取当前系统时间
        bsadmin.setInserttime(new Date());
        bsadminService.addBsadmin(bsadmin);
        BsadminPowerVos vos = new BsadminPowerVos();
        vos.setId(bsadmin.getId());
        vos.getPowerid().add(1);
        vos.getPowerid().add(2);
        vos.getPowerid().add(3);
        bsadminPowerService.saveBsadminPowerById(vos);
        return true;
    }

    //删除管理员
    @RequestMapping("deleteBsadminById")
    public @ResponseBody Boolean deleteBsadminById(Bsadmin bsadmin){
        bsadminService.deleteBsadminById(bsadmin);
        return true;
    }
//************************************************************************

    //根据当前管理员的分店id查询该分店管理员信息
    @RequestMapping("/findBusinessMin")
    public String findBusinessMin(HttpSession httpSession,HttpServletRequest request, Integer bsid,Integer pageNum,String username) {
        if(pageNum == null){
            pageNum =1;
        }
        Bsadmin bsadmin1 = (Bsadmin) httpSession.getAttribute("bsadmin1");
        bsid = bsadmin1.getBsid();
        PageBean<Bsadmin> businessMinList = bsadminService.findBusinessMin(pageNum,bsid,username);
        request.setAttribute("businessMinList", businessMinList);
        request.setAttribute("username",username);
        return "branch_oa/admin-list";
    }

     @RequestMapping("/power")
    public @ResponseBody Boolean power(Bsadmin bsadmin){
        bsadminService.stateBsAdmin(bsadmin);
        return true;
    }

    //根据分店id查询分店信息
    @RequestMapping("/findbStoreById")
    public String findbStoreById(HttpSession httpSession, Integer bsid){
        BranchStore branchStore = branchStoreService.findbStoreById(bsid);
        httpSession.setAttribute("branchStore",branchStore);
        return "branch_oa/page-add";
    }

    //页面设置中的修改功能
    @RequestMapping("/updateBranchStorer")
    public @ResponseBody Boolean updateBranchStorer(@RequestBody BranchStore branchStore){
           branchStoreService.byIdUpdateBranchStore(branchStore);
           return true;
    }


}
